package com.liufeng.myheart;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.trace.OnEntityListener;
import com.baidu.trace.OnStartTraceListener;
import com.baidu.trace.OnTrackListener;
import com.baidu.trace.TraceLocation;
import com.liufeng.myheart.config.ConfigActivity;
import com.liufeng.myheart.util.GsonService;
import com.liufeng.myheart.util.TraceUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by liufeng on 2016/7/12.
 */
public class MapActivity extends AppCompatActivity {

    private Button hisheart;
    private Button myheart;
    private ImageView heartImage;
    private TextView time;
    private ImageButton location;
    private ImageButton config;

    private MapView mapView;
    private BaiduMap baiduMap;
    private String my = "";
    private String his = "";
    private SharedPreferences myspf;
    private static final String TAG = "Trace";
    private BitmapDescriptor realtimeBitmap = BitmapDescriptorFactory
            .fromResource(R.drawable.icon_gcoding);
    private BitmapDescriptor bmStart = BitmapDescriptorFactory.fromResource(R.drawable.icon_start);
    private BitmapDescriptor bmEnd = BitmapDescriptorFactory.fromResource(R.drawable.icon_end);
    private boolean realtime;
    private boolean isshow;
    private boolean updatemap;
    private boolean isstop;
    Handler handler;
    SimpleDateFormat MySdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    ProgressDialog progressDialog;
    private OnEntityListener hisRealTimeListener = null;
    private OnTrackListener hisHistoryListener = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        initComponent();
        isstop = false;
        realtime = true;
        isshow = false;
        updatemap = true;
        handler = new Handler();
        progressDialog = new ProgressDialog(MapActivity.this, AlertDialog.THEME_HOLO_LIGHT);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在查询轨迹,请稍后...");
        myspf = getSharedPreferences("myheart",
                Context.MODE_PRIVATE);
        initMyTrace();
        initHistrace();
    }

    /**
     * 初始化组件
     */
    private void initComponent() {
        hisheart = (Button) findViewById(R.id.hisheart);
        myheart = (Button) findViewById(R.id.myheart);
        mapView = (MapView) findViewById(R.id.bmapView);
        time = (TextView) findViewById(R.id.time);
        location = (ImageButton) findViewById(R.id.location);
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updatemap = true;
                Toast.makeText(MapActivity.this, "正在定位,请稍候...", Toast.LENGTH_SHORT).show();
            }
        });
        heartImage = (ImageView) findViewById(R.id.heart);
        heartImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeHistory();
            }
        });
        config = (ImageButton) findViewById(R.id.config);
        config.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MapActivity.this, ConfigActivity.class));
            }
        });
        baiduMap = mapView.getMap();
        mapView.showZoomControls(false);
        baiduMap.setMyLocationEnabled(true);
        hisRealTimeListener = new OnEntityListener() {
            // 查询失败回调接口
            @Override
            public void onRequestFailedCallback(String arg0) {
                Log.e(TAG, "entity请求失败回调接口消息 : " + arg0);
            }

            // 查询entity回调接口，返回查询结果列表
            @Override
            public void onQueryEntityListCallback(String arg0) {
                RealtimeTrackData realtimeTrackData = GsonService.parseJson(arg0, RealtimeTrackData.class);
                LatLng realtimePoint = realtimeTrackData.getRealtimePoint();
                if (realtimePoint != null) {
                    drawRealtimePoint(realtimePoint);
                }
            }

            @Override
            public void onReceiveLocation(TraceLocation traceLocation) {
                drawMyLocation(traceLocation);

            }
        };
        hisHistoryListener = new OnTrackListener() {
            @Override
            public void onRequestFailedCallback(String s) {

            }

            @Override
            public void onQueryHistoryTrackCallback(String s) {
                progressDialog.dismiss();
                HistoryTrackData historyTrackData = GsonService.parseJson(s, HistoryTrackData.class);
                List<LatLng> latLngList = new ArrayList<LatLng>();
                if (historyTrackData != null && historyTrackData.getStatus() == 0) {
                    if (historyTrackData.getListPoints() != null) {
                        latLngList.addAll(historyTrackData.getListPoints());
                    }

                    // 绘制历史轨迹
                    drawHistoryTrack(latLngList, historyTrackData.distance);

                }
            }
        };
    }

    /**
     * 切换为历史轨迹模式
     */
    private void changeHistory() {
        if (his.isEmpty()) {
            return;
        } else {
            if (realtime) {
                heartImage.setImageResource(R.drawable.heart_blue);
                time.setVisibility(View.VISIBLE);
                time.setText(MySdf.format(calendar.getTime()));
                time.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        selectTime();
                    }
                });
                isshow = false;
                progressDialog.show();
                realtime = false;
            } else {
                heartImage.setImageResource(R.drawable.heart_all);
                time.setVisibility(View.GONE);
                realtime = true;
            }
            updatemap = true;
        }
    }

    /**
     * 选择时间弹窗
     */
    private void selectTime() {
        DatePickerDialog pickerDialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker,
                                  int year, int month, int dayOfMonth) {
                calendar.set(year, month, dayOfMonth);
                time.setText(MySdf.format(calendar.getTime()));
                isshow = false;
                progressDialog.show();
                updatemap = true;
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        pickerDialog.setTitle("日期选择");
        pickerDialog.show();
    }

    /**
     * 初始化获取另一半轨迹
     */
    private void initHistrace() {
        his = myspf.getString("his", "");
        if ("".equals(his)) {
            hisheart.setVisibility(View.VISIBLE);
            hisheart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    bindId();
                }
            });
        } else {
            heartImage.setImageResource(R.drawable.heart_all);
            hisheart.setText(R.string.right);
            showHisTrace();
        }


    }

    /**
     * 显示另一半的实时轨迹
     */
    private void showHisTrace() {

        //查询实时轨迹
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isstop) {
                    handler.postDelayed(this, 5000);

                    if (realtime) {
                        TraceUtil.queryRealTimePoint(his, hisRealTimeListener);
                    } else {
                        String selectedtime = time.getText().toString();
                        String now = MySdf.format(Calendar.getInstance().getTime());
                        if (!isshow) {
                            long startTime, endTime;
                            calendar.set(Calendar.HOUR_OF_DAY, 0);
                            calendar.set(Calendar.MINUTE, 0);
                            calendar.set(Calendar.SECOND, 0);
                            startTime = calendar.getTimeInMillis();
                            if (now.equals(selectedtime)) {
                                isshow = false;
                                Calendar instance = Calendar.getInstance();
                                endTime = instance.getTimeInMillis();
                            } else {
                                isshow = true;
                                calendar.add(Calendar.HOUR_OF_DAY, 24);
                                endTime = calendar.getTimeInMillis();
                                calendar.add(Calendar.HOUR_OF_DAY, -24);
                            }

                            TraceUtil.queryHistoryTrack(his, startTime, endTime, hisHistoryListener);
                        }
                    }
                    TraceUtil.queryMyLocation(hisRealTimeListener);
                }
            }
        }, 500);

    }

    private void drawMyLocation(TraceLocation traceLocation) {
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy((float) traceLocation.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(traceLocation.getDirection()).latitude(traceLocation.getLatitude())
                .longitude(traceLocation.getLongitude()).speed(traceLocation.getSpeed())
                .build();
        baiduMap.setMyLocationData(locData);
    }

    /**
     * 绘制历史轨迹
     *
     * @param latLngList
     * @param distance
     */
    private void drawHistoryTrack(List<LatLng> latLngList, double distance) {
        baiduMap.clear();
        if (latLngList == null || latLngList.size() == 0) {
            Looper.prepare();
            Toast.makeText(this, "当前查询无轨迹点", Toast.LENGTH_SHORT).show();
            Looper.loop();
            //resetMarker();
        } else if (latLngList.size() > 1) {

            LatLng llC = latLngList.get(0);
            LatLng llD = latLngList.get(latLngList.size() - 1);
            LatLngBounds bounds = new LatLngBounds.Builder()
                    .include(llC).include(llD).build();
            if (updatemap) {
                MapStatusUpdate msUpdate = MapStatusUpdateFactory.newLatLngBounds(bounds);
                baiduMap.setMapStatus(msUpdate);
                updatemap = false;
            }

            // 添加起点图标
            OverlayOptions startMarker = new MarkerOptions()
                    .position(latLngList.get(latLngList.size() - 1)).icon(bmStart)
                    .zIndex(9).draggable(true);
            baiduMap.addOverlay(startMarker);
            // 添加终点图标
            OverlayOptions endMarker = new MarkerOptions().position(latLngList.get(0))
                    .icon(bmEnd).zIndex(9).draggable(true);
            baiduMap.addOverlay(endMarker);
            // 添加路线（轨迹）
            OverlayOptions polyline = new PolylineOptions().width(10)
                    .color(Color.RED).points(latLngList);

            baiduMap.addOverlay(polyline);


        }
    }


    /**
     * 绘制实时点
     */
    private void drawRealtimePoint(LatLng point) {

        baiduMap.clear();

        if (updatemap) {
            MapStatus mMapStatus = new MapStatus.Builder().target(point).zoom(20).build();

            MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            baiduMap.setMapStatus(mapStatusUpdate);
            updatemap = false;
        }

        OverlayOptions overlay = new MarkerOptions().position(point)
                .icon(realtimeBitmap).zIndex(9).draggable(true);

        baiduMap.addOverlay(overlay);
    }

    /**
     * 初始化上传我的轨迹
     */
    private void initMyTrace() {

        my = myspf.getString("my", "");
        if ("".equals(my)) {
            myheart.setVisibility(View.VISIBLE);
            myheart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    createId();
                }
            });
        } else {
            startMyTrace();
        }


    }

    /**
     * 开始记录我的轨迹
     */
    private void startMyTrace() {

        //实例化开启轨迹服务回调接口
        OnStartTraceListener startTraceListener = new OnStartTraceListener() {
            //开启轨迹服务回调接口（arg0 : 消息编码，arg1 : 消息内容，详情查看类参考）
            @Override
            public void onTraceCallback(int arg0, String arg1) {
                Log.d(TAG, arg0 + ":" + arg1);
            }

            //轨迹服务推送接口（用于接收服务端推送消息，arg0 : 消息类型，arg1 : 消息内容，详情查看类参考）
            @Override
            public void onTracePushCallback(byte arg0, String arg1) {
                Log.d(TAG, arg0 + ":" + arg1);
            }
        };
        TraceUtil.startTrace(getApplicationContext(), my, startTraceListener);


    }

    /**
     * 绑定另一半的id
     */
    private void bindId() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_phone, null);
        final EditText phoneText = (EditText) inflate.findViewById(R.id.phone);
        AlertDialog.Builder builder = new AlertDialog.Builder(this, 3);
        builder.setTitle(R.string.app_name);
        builder.setView(inflate);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String s = phoneText.getText().toString();
                if (s.isEmpty()) {
                    bindId();
                } else {
                    his = s;
                    SharedPreferences.Editor edit = myspf.edit();
                    edit.putString("his", his);
                    edit.commit();
                    hisheart.setText(R.string.right);
                    heartImage.setImageResource(R.drawable.heart_all);
                    showHisTrace();
                }

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.create().show();
    }

    /**
     * 生成唯一id
     */
    private void createId() {
        //my="liufeng";
//        my="zouhongyan";
        SharedPreferences.Editor edit = myspf.edit();
        edit.putString("my", my);
        edit.commit();
        myheart.setVisibility(View.GONE);
        startMyTrace();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realtimeBitmap.recycle();
        bmStart.recycle();
        bmEnd.recycle();
        mapView.onDestroy();
        isstop = true;
        MyApplication.client.setOnEntityListener(null);
        MyApplication.client.setOnTrackListener(null);
        Log.i(TAG, "onDestroy");
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        Log.i(TAG, "onPause");
    }


    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        Log.i(TAG, "onResume");
    }
}
